import React, { PureComponent } from 'react'
import { SwipeListView } from 'react-native-swipe-list-view'
import { StyleSheet, Text, View } from 'react-native'
import IMController from 'src/utils/IMController'
import NavigationUtil from 'src/utils/NavigationUtil'
import PropTypes from 'prop-types'
import { ScaleS, ScaleT, WIDTH, HEIGHT } from 'src/utils/ScreenUtil'
import CustomButton from 'src/components/button/CustomButton'
import MessageItem from 'src/components/message/MessageItem'
import EmptyView from 'src/components/empty-view'
import CustomImage from '../image/CustomImage'

export default class MessageList extends PureComponent {
  static propTypes = {
    messageList: PropTypes.array,
    updateImState: PropTypes.func,
    navigatePage: PropTypes.string,
    userId: PropTypes.number,
    realUserId: PropTypes.number,
    emptyTip: PropTypes.string,
    notLoginTip: PropTypes.string,
    showEmpty: PropTypes.bool
  }

  static defaultProps = {
    contactList: [],
    showEmpty: true
  }

  constructor (props) {
    super(props)
    this.getErrorSource = this.getErrorSource.bind(this)
    this.listHeaderComponent = this.listHeaderComponent.bind(this)
    this.onRefresh = this.onRefresh.bind(this)
    this.state = {
      refreshing: false,
      showEmpty: true,
      fHeight: 0
    }
  }

  componentDidMount () {
    console.info(this.props.messageList, 'contactListcontactListcontactList')
  }

  componentWillFocus () {
    console.info(this.props.messageList, 'contactListcontactListcontactList11')
  }

  render () {
    const { messageList } = this.props
    const { refreshing, showEmpty } = this.state
    return (
      <SwipeListView
        useFlatList={true}
        style={styles.flatList}
        data={messageList}
        ListHeaderComponent={this.listHeaderComponent}
        renderItem={this._renderItem}
        renderHiddenItem={this.renderHiddenItem}
        rightOpenValue={-75}
        disableRightSwipe={true}
        keyExtractor={this._keyExtractor}
        ListEmptyComponent={this._listEmptyComponent}
        refreshing={refreshing}
        onLayout={this._onLayout}
        bounces={!showEmpty}
        onRefresh={this.refresh ? this.onRefresh : null}
      />
    )
  }

  _onLayout = (e) => {
    const height = e.nativeEvent.layout.height
    if (this.state.fHeight < height) {
      this.setState({
        fHeight: height
      })
    }
  }

  onRefresh () {
    console.info('_onRefresh')
  }

  listHeaderComponent = () => null

  /**
   * 消息缺省页
   * @returns {*}
   * @private
   */
  _listEmptyComponent = () => {
    const { userId, notLoginTip, realUserId } = this.props
    const { showEmpty, fHeight } = this.state
    return showEmpty ? (
      <View style={{ height: fHeight }}>
        <View style={styles.emptyView}>
          <CustomImage style={styles.emptyImg} source={realUserId ? require('src/imgC/message/default_message.png') : require('src/imgC/message/default_empty.png')}/>
          {!realUserId && <CustomButton style={styles.btnView} onPress={this._goLogin}>
            <Text style={styles.btnLabel}>{userId ? (realUserId ? null : '完善') : '登录'}</Text>
          </CustomButton>}
        </View>
      </View>
    ) : null
  }

  /**
   * 去登录
   * @private
   */
  _goLogin = () => {
    NavigationUtil.jumpLogin()
  }

  _keyExtractor = (item, index) => item.account || index

  /**
   * 去聊天
   * @param account
   */
  goChat = ({ account }) => {
    const { navigatePage } = this.props
    this.props.updateImState({
      selToID: account,
      msgArray: [],
      currentSessionId: `p2p-${account}`
    })
    IMController.updateUnreadInfo(`p2p-${account}`)
    NavigationUtil.navigate(navigatePage)
  }

  _renderItem = data => {
    const { item } = data
    return (
      <CustomButton onPress={this.goChat} params={{ account: item.account }}>
        <MessageItem item={item} errorSource={this.getErrorSource(item)}/>
      </CustomButton>
    )
  }

  /**
   * 获取失败的时候的头像
   * @param item
   */
  getErrorSource (item) {
  }

  renderHiddenItem = data => {
    const { item } = data
    return (
      <CustomButton onPress={this.delChat} params={{ toId: item.account }}>
        <View style={styles.rightBtn}>
          <Text style={{ color: 'white' }}>删除</Text>
        </View>
      </CustomButton>
    )
  }

  /**
   * 删除聊天
   * @param account
   */
  delChat = ({ toId: account }) => {
    // 删除聊天记录
    IMController.delChat({ toId: account }).then(() => {
      // 处理聊天数据
      const { messageList } = this.props
      const contactListNew = [...messageList]
      contactListNew.map((itemMap, indexMap) => {
        if (itemMap.account == account) {
          contactListNew.splice(indexMap, 1)
        }
        return itemMap
      })
      IMController.checkRedDot(contactListNew)
      this.props.updateImState({
        contactList: contactListNew
      })
    })
  }
}

const styles = StyleSheet.create({
  flatList: {
    flex: 1,
    backgroundColor: 'white'
  },
  chatItem: {
    alignItems: 'center',
    flexDirection: 'row',
    width: ScaleS(375),
    paddingHorizontal: ScaleS(20),
    backgroundColor: '#ffffff',
    marginVertical: ScaleS(20)
  },
  rightBtn: {
    position: 'absolute',
    top: ScaleS(20),
    right: 0,
    height: ScaleS(52),
    width: ScaleS(75),
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'red',
    color: 'white'
  },
  headerImg: {
    width: ScaleS(52),
    height: ScaleS(52),
    borderRadius: ScaleS(26),
    marginRight: ScaleS(14),
    resizeMode: 'cover'
  },
  itemMiddle: {
    height: ScaleS(52),
    justifyContent: 'space-between',
    flex: 1
  },
  itemMiddleText: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    width: ScaleS(200)
  },
  itemName: {
    fontSize: ScaleT(18),
    fontWeight: '600',
    color: '#000',
    marginRight: ScaleS(15)
  },
  itemCompany: {
    fontSize: ScaleT(14),
    color: '#999999',
    overflow: 'hidden',
    flex: 1
  },
  itemMsg: {
    width: ScaleS(200),
    // overflow: 'hidden',
    fontSize: ScaleT(14),
    color: '#999999'
  },
  itemMsgTime: {
    fontSize: ScaleT(14),
    color: '#D1D1D1',
    alignSelf: 'flex-start'
  },
  unread: {
    position: 'absolute',
    bottom: ScaleS(0),
    right: ScaleS(20),
    width: ScaleS(16),
    height: ScaleS(16),
    backgroundColor: '#EF5E6A',
    borderRadius: ScaleS(8),
    alignItems: 'center',
    justifyContent: 'center'
  },
  unreadCount: {
    fontSize: ScaleT(10),
    fontWeight: '500',
    color: '#FFFFFF'
  },
  emptyView: {
    flex: 1,
    position: 'absolute',
    bottom: 0
  },
  emptyImg: {
    width: WIDTH,
    height: ScaleS(342)
  },
  btnView: {
    position: 'absolute',
    left: ScaleS(81),
    top: ScaleS(150),
    borderRadius: ScaleS(4),
    backgroundColor: '#FFE400',
    paddingHorizontal: ScaleS(22),
    paddingVertical: ScaleS(8),
    justifyContent: 'center',
    alignItems: 'center'
  },
  btnLabel: {
    fontSize: ScaleT(12),
    fontWeight: '500',
    color: '#3C3C3C'
  }
})
